#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;


void recv_thread(int fd)
{
    char buf[1024] = {};    
    while(1) {
        memset(buf, 0, 1024);
        int len = recvfrom(fd, buf, sizeof(buf), 0, NULL, NULL);
        if(len == -1) {
            perror("recv failed");
        }
        else {
            printf("[%d] %s\n", len, buf);
        }
    }
}

void send_thread(int fd)
{
    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(8000);
    saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    char buf[1024] = {};
    while(1) {
        memset(buf, 0, 1024);
        cout << "输入消息：";
        cin.getline(buf, 1024);
        if(strlen(buf) == 0)
            continue;
        if(strcmp(buf, "quit") == 0)
            exit(0);
        int len = sendto(fd, buf, strlen(buf) + 1, 0, (struct sockaddr*)&saddr, sizeof(saddr));
        if(len == -1) {
            perror("send failed");
        }
    }
}


int main()
{
    // 1. 创建 soclet 连接
    int clifd = socket(AF_INET, SOCK_DGRAM, 0);
    if(clifd == -1) {
        perror("create socket failed");
        return 0;
    }
    else {
        cout << "create socket successful\n";
    }

    // 2. 绑定 IP 地址和端口号（可选）

    // 3. 发送/接收消息
    thread t_recv(recv_thread, clifd), t_send(send_thread, clifd);
    t_recv.join();
    t_send.join();

    // 4. 关闭 socket 连接
    close(clifd);

    return 0;
}